import React, { useState, useEffect } from 'react'
import { Card, Button, Table, Modal, Form, Input, message } from 'antd';
import { PlusCircleOutlined } from '@ant-design/icons'
import { useDispatch, useSelector, shallowEqual } from 'react-redux'
import ajax from '../../service/ajax'
import { saveCategoryListAction } from '../../store/actionCreators/admin'



export default function Category(props) {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [categoryID, setCategoryId] = useState() // 设置商品的id
  const [cateName, setCateName] = useState() // 设置商品的名字
  const [isUpdate, setIsUpdate] = useState(false)
  const dispatch = useDispatch()
  const { categoryList } = useSelector((state) => ({
    categoryList: state.adminInfo.categoryList
  }), shallowEqual)
  // 获得表单实例
  const [form] = Form.useForm()

  const columns = [
    {
      title: '分类名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '操作',
      // dataIndex: '_id',
      key: 'opera',
      align: 'center',
      width: '15%',
      render: (categoryObj) => (<Button type="link" onClick={e => showModal(categoryObj)}>修改分类</Button>)
    },
  ];

  useEffect(() => {
    dispatch(saveCategoryListAction())
  }, [dispatch])

  // 修改分类的函数
  const updateCategory = async (_id, name) => {
    if(!_id || !name) return;
    let result = await ajax.post('/manage/category/update', { categoryId: categoryID, categoryName: cateName })
    const { status, msg } = result
    if (status === 0) {
      message.success('修改分类成功')
      dispatch(saveCategoryListAction())
      setIsModalVisible(false)
      form.setFieldsValue({
        categoryName: ''
      })
    } else {
      message.warning(msg)
    }
  }

  // 新增分类的函数

  const addCategory = async () => {
    let categoryName = form.getFieldsValue().categoryName
    if (!categoryName) { message.warning('分类名不能为空'); return }
    let result = await ajax.post('/manage/category/add', { categoryName })
    if (result.status === 0) {
      message.success('分类添加成功')
      dispatch(saveCategoryListAction())
      setIsModalVisible(false);
      form.resetFields()
    } else {
      message.warning(result.msg)
    }
  }

  // 点击后显示模态框
  const showModal = (categoryObj) => {
    if (isUpdate) setIsUpdate(false)
    const { _id, name } = categoryObj
    if (_id && name) {
      // 如果_id和name不为undefined，表示点击的是修改
      setCategoryId(_id)
      setCateName(name)
      setIsUpdate(true)
      form.setFieldsValue({
        categoryName: name
      })
      // updateCategory(_id, name)
    }


    setIsModalVisible(true);
  };

  // 点击模态框确定后的回调
  const handleOk = () => {
    if (!isUpdate) {
      // 新增分类
      addCategory()
    } else {
      updateCategory(categoryID, cateName)
    }
  };

  // 点击模态框取消后的回调
  const handleCancel = () => {
    setIsModalVisible(false);
    form.setFieldsValue({
      categoryName: ''
    })
  };

  return (
    <Card extra={<Button type="primary" onClick={showModal}><PlusCircleOutlined />添加</Button>}>
      <Table
        bordered
        dataSource={categoryList}
        columns={columns}
        rowKey="_id"
        pagination={{
          pageSize: 4,
          showQuickJumper: true
        }}
      />;

      <Modal
        getContainer={false}
        title={isUpdate ? '修改分类' : '新增分类'}
        visible={isModalVisible}
        okText="确定"
        cancelText="取消"
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          initialValues={{
            categoryName: cateName
          }}
          form={form}
        >
          <Form.Item
            name="categoryName"
            rules={[
              {
                required: true,
                message: "分类名必须输入"
              }
            ]}
          >
            <Input placeholder="请输入分类名" />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  )
}